import 'dart:math';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:largefriends/res/lf_double_ext.dart';
import 'package:swipable_stack/swipable_stack.dart';

import '../../entity/entities/lf_user_entity.dart';
import '../../res.dart';
import '../../res/lf_color.dart';
import '../../res/lf_fonts.dart';
import '../../res/lf_text_style.dart';
import '../../res/lf_widget_ext.dart';
import '../../res/strings/lf_strings.dart';
import '../../utils/lf_logger.dart';
import '../../widgets/common_failed_page.dart';
import '../../widgets/custom_cache_image.dart';
import '../lf_base_controller.dart';
import '../lf_payment/lf_payment_logic.dart';
import '../lf_profile/lf_profile_logic.dart';
import 'lf_search_filter/lf_search_filter_logic.dart';
import 'lf_spark_empty.dart';
import 'lf_spark_loading.dart';
import 'lf_spark_waiting.dart';
import 'lf_tab_spark_logic.dart';

class LfTabSparkPage extends StatefulWidget {
  const LfTabSparkPage({super.key});

  @override
  State<LfTabSparkPage> createState() => _LfTabSearchPageState();
}

class _LfTabSearchPageState extends State<LfTabSparkPage>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  final logic = Get.put(LfTabSparkLogic());

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: ShaderMask(
            shaderCallback: (Rect bounds) {
              return LinearGradient(
                begin: const Alignment(-0.5, -0.9),
                end: const Alignment(0.5, 0.9),
                colors: [colorFF007F, colorFF007F, colorBF00FF, colorBF00FF],
              ).createShader(Offset.zero & bounds.size);
            },
            blendMode: BlendMode.srcATop,
            child: Text(
              'Flame',
              style: TextStyle(
                  fontSize: 28.sp,
                  fontFamily: fontYoungSerif,
                  letterSpacing: 1.2),
            )),
      ),
      body: GetBuilder<LfTabSparkLogic>(
        builder: (logic) {
          if (logic.showSparkLimit) {
            return LfSearchWaiting(
              timeOver: () {
                logic.authService.limitEntity = null;
                logic.request();
              },
            );
          }
          if (logic.state == LoadingState.init ||
              logic.state == LoadingState.loading) {
            return const LfSparkLoading();
          }
          if (logic.dataList.isEmpty) {
            if (logic.state == LoadingState.empty) {
              return LfSearchEmptyWidget(
                title: strNoBodyAround.tr,
                content: strPickNoBodyTip.tr,
                actionTitle: strSearchMatches.tr,
                action: () {
                  toLfSearchFilter();
                },
              );
            }
            return CommonFailedPage(
              retry: () {
                logic.request();
              },
            );
          }
          return Stack(
            children: [
              _userItems(),
              Positioned(
                bottom: 80.h,
                left: 20.w,
                right: 20.w,
                child: Row(
                  children: [
                    Obx(() {
                      if (logic.showRemind.isTrue &&
                          logic.controller.currentIndex != 0) {
                        return Visibility(
                          visible: logic.showRemind.isTrue,
                          child: InkWell(
                            child: Container(
                              alignment: Alignment.center,
                              width: 36.w,
                              height: 36.w,
                              child: Image.asset(Res.spark_recall,
                                  width: 30.r,
                                  height: 30.r,
                                  color: colorFEFEFE).shadeMask,
                            ),
                            onTap: () {
                              if (logic.authService.currentAccount!.isGold()) {
                                if (logic.showRemind.isTrue) {
                                  logic.controller.rewind();
                                }
                                logic.showRemind.value = false;
                              } else {
                                toPayment();
                              }
                            },
                          ),
                        );
                      } else {
                        return 40.w.sbw;
                      }
                    }),
                    emptyExpand,
                    InkWell(
                      child: Image.asset(
                        Res.new_spark_pass,
                        width: 60.r,
                        height: 60.r,
                        color: color514F62 ,
                      ),
                      onTap: () {
                        lfLogger.e(
                            "logic.controller.currentIndex==${logic.controller.currentIndex}");
                        logic.like(
                            logic.dataList[logic.controller.currentIndex]);
                        logic.controller
                            .next(swipeDirection: SwipeDirection.left);
                      },
                    ),
                    emptyExpand,
                    InkWell(
                      child: Image.asset(
                        Res.icon_like,
                        width: 64.r,
                        height: 64.r,
                      ),
                      onTap: () {
                        logic.pass(
                            logic.dataList[logic.controller.currentIndex]);
                        logic.controller
                            .next(swipeDirection: SwipeDirection.right);
                      },
                    ),
                    emptyExpand,
                    40.r.sbw
                  ],
                ),
              )
            ],
          );
        },
      ),
    );
  }

  _userItems() {
    return Positioned.fill(
        child: SwipableStack(
      builder: (context, swipeProperty) {
        LfUserEntity userEntity = logic.dataList[swipeProperty.index];
        return Padding(
          padding:
              EdgeInsets.only(top: 1.h, bottom: 140.h, right: 10.w, left: 10.w),
          child: Card(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(24.r)),
            ),
            clipBehavior: Clip.antiAlias,
            child: InkWell(
              child: Stack(
                children: [
                  Positioned.fill(
                      child: CustomCacheImage(
                    imageUrl: userEntity.avatar,
                    radius: 10.r,
                  )),
                  Align(
                    alignment: Alignment.bottomLeft,
                    child: Padding(
                      padding:
                          EdgeInsets.symmetric(horizontal: 6.w, vertical: 10.w),
                      child: IntrinsicHeight(
                        child: ClipRRect(
                          borderRadius: 10.r.radius,
                          child: BackdropFilter(
                            filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                            child: Container(
                              padding: EdgeInsets.symmetric(
                                  vertical: 10.h, horizontal: 10.w),
                              constraints: BoxConstraints(
                                  minWidth: ScreenUtil().screenWidth,
                                  maxWidth: ScreenUtil().screenWidth,
                                  minHeight: 60.h),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  Row(
                                    children: [
                                      Flexible(
                                        child: Text(
                                          userEntity.getNameWithGenderAge(),
                                          style: lfTextStyle(
                                              sp: 16.sp,
                                              fontFamily: fontBold,
                                              color: colorFEFEFE),
                                        ),
                                      ),
                                      userEntity.isVerified()
                                          ? Padding(
                                              padding:
                                                  EdgeInsets.only(left: 5.w),
                                              child: Image.asset(
                                                  Res.ic_verified,
                                                  width: 16.r),
                                            )
                                          : empty,
                                      userEntity.isGold()
                                          ? Padding(
                                              padding:
                                                  EdgeInsets.only(left: 5.w),
                                              child: Image.asset(
                                                Res.icon_premium,
                                                width: 18.r,
                                                color: colorFF007F,
                                              ),
                                            )
                                          : empty,
                                    ],
                                  ),
                                  4.h.sbh,
                                  Text(userEntity.getLiveIn(),
                                      style: lfTextStyle(
                                          sp: 16.sp,
                                          fontFamily: fontRegular,
                                          color: colorFEFEFE))
                                ],
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              onTap: () {
                toProfilePage(uid: userEntity.userId!, userEntity: userEntity);
              },
            ),
          ),
        );
      },
      controller: logic.controller,
      overlayBuilder: (context, properties) {
        final opacity = min(properties.swipeProgress, 1.0);
        final isRight = properties.direction == SwipeDirection.right;
        final isLeft = properties.direction == SwipeDirection.left;
        if (isRight) {
          return Opacity(
            opacity: opacity,
            child: Stack(
              children: [
                Positioned(
                  left: 40.w,
                  top: 60.h,
                  child: Image.asset(
                    Res.icon_like,
                    height: 88.r,
                    width: 88.r,
                  ),
                )
              ],
            ),
          );
        } else if (isLeft) {
          return Opacity(
            opacity: opacity,
            child: Stack(
              children: [
                Positioned(
                  right: 40.w,
                  top: 60.h,
                  child: Image.asset(
                    Res.spark_item_dislike,
                    height: 88.r,
                    width: 88.r,
                  ),
                )
              ],
            ),
          );
        }
        return empty;
      },
      // allowVerticalSwipe: false,
      onWillMoveNext: (index, direction) {
        if (logic.authService.canSpark() == false) {
          logic.showSparkLimit = true;
          logic.update();
          return false;
        }
        final allowedActions = [
          SwipeDirection.right,
          SwipeDirection.left,
        ];
        return allowedActions.contains(direction);
      },
      onSwipeCompleted: (index, direction) {
        ///do nothing
        if (direction == SwipeDirection.right) {
          logic.like(logic.dataList[index]);
        } else {
          logic.pass(logic.dataList[index]);
        }
        if (index == logic.dataList.length - 1) {
          logic.request();
        }
      },
      itemCount: logic.dataList.length,
    ));
  }

  @override
  bool get wantKeepAlive => true;
}
